package ge.lowlevel.js;


import ge.lowlevel.SoundEngine;

public class JSSoundEngine extends SoundEngine
{
	 
	private float musicVolume;
	public JSSoundEngine ()
	{
		musicVolume = 1f; 
		init();
	}
	private native void init()
	/*-{
		$wnd.songs = new Array();
		$wnd.ends = new Array();
		$wnd._volume = 1;
		var _isFormatValid = function (formato)
		{
			if(formato == "ogg" || formato == "wav" || formato == "mp3")
				return true;
			else
				return false;
		}
		$wnd._setSource = function(audio,urlSound)
		{
		 	var source = $doc.createElement("source"); 
	 	
			 var punto = urlSound.lastIndexOf('.');
			 var formato = urlSound.substr(punto+1);
			 if(!_isFormatValid(formato))
					throw "Tipo de Musica no compatible "+urlSound+" con formato "+formato;
					
			 source.setAttribute("src",urlSound);
			 source.setAttribute("type","audio/"+formato);
			 audio.appendChild(source);
		}
	}-*/;
	@Override
	public native void add(String id, String urlSound)
	/*-{
	 	var audio;
		if(id in $wnd.songs)
		{
			audio = $wnd.songs[id];
			var source = document.createElement("source");
			source.setAttribute("src",urlSound);
			audio.appendChild(source);
		}
		else
		{
	 		audio = $doc.createElement("audio");
	 		var source = document.createElement("source");
			source.setAttribute("src",urlSound);
			audio.appendChild(source);
	 		$wnd.songs[id] = audio;
	 		$wnd.ends[id] = false;
		}
	
	 	$wnd._setSource(audio,urlSound);
	}-*/;
	@Override
	public native void play(String id)
	/*-{
		 if(id in $wnd.songs)
		 {
		 	var audio = $wnd.songs[id];
		 	audio.volume = $wnd._volume;
		 	$wnd.ends[id] = false;
		 	//$wnd.alert(audio+" playing");
			
			audio.addEventListener( "ended", function()
			{
			 	 
				$wnd.ends[id] = true;
			},false);
			
				
			audio.load();
			
			audio.play();
		 }
		  
		 
		 //$wnd.alert(audio.currentTime);
		 
	}-*/;
	@Override
	public native boolean isEnd(String id)
	/*-{
	  
	 		
		return $wnd.ends[id];
	}-*/;
	@Override
	public native void stop(String id)
	/*-{
		 if(id in $wnd.songs)
		 {
		 	var audio = $wnd.songs[id];
			audio.pause();
			$wnd.ends[id] = true;
		 
			 
		 }
	}-*/;
	
	@Override
	public native void pause(String id)
	/*-{
		 if(id in $wnd.songs)
		 {
		 	var audio = $wnd.songs[id];
			audio.pause();
			$wnd.ends[id] = false;
			 
		 }
	}-*/;
	@Override
	public native void setVolume(double volume)
	/*-{
			$wnd._volume = volume;	//se almacena
			for( i in  $wnd.songs)
			{
				$wnd.songs[i].volume = volume;
			}
	}-*/;
	
	
}
